package pl.freetimetool.service;

import java.util.Collection;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessException;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

import pl.freetimetool.dao.AccountDao;
import pl.freetimetool.domain.Account;
import pl.freetimetool.domain.AccountRole;
import pl.freetimetool.exceptions.UserExistsException;
import pl.freetimetool.exceptions.UserNotFoundException;

@Transactional
@Repository
public class AccountServiceImpl implements AccountService {
	@Autowired
	AccountDao accountDao;

	public void registerAccount(final Account account, final List<AccountRole> ar) throws UserExistsException {
		try {
			this.accountDao.findUsername(account.getUsername());
			throw new UserExistsException();
		} catch (final UserNotFoundException une) {
			this.accountDao.save(account);
			account.setPassword(account.getPassword());
			for (final AccountRole arole : ar) {
				account.addAccountRole(arole);
			}
		}
	}

	@Transactional(readOnly = true)
	public Collection<Account> listAccounts(final Collection<AccountRole> roles) {
		return this.accountDao.listAccounts(roles);
	}

	@Transactional(readOnly = true)
	public Account getAccount(final String username) {
		try {
			return this.accountDao.findUsername(username);
		} catch (final UserNotFoundException e) {
			e.printStackTrace();
			return null;
		}
	}

	@Transactional(readOnly = true)
	public void removeAccount(final String username) {
		Account acc = null;
		try {
			acc = this.accountDao.findUsername(username);
		} catch (final UserNotFoundException e) {
		}
		if (acc != null) {
			this.accountDao.remove(acc);
		}
	}

	public UserDetails loadUserByUsername(final String username) throws UsernameNotFoundException, DataAccessException {
		try {
			return this.accountDao.findUsername(username);
		} catch (final UserNotFoundException e) {
			throw new UsernameNotFoundException(username);
		}
	}
}
